package pas.book.font;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.zip.Deflater;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class Convert {

    public static void main(String[] args) throws Exception {

        ZipOutputStream zip = new ZipOutputStream(new FileOutputStream("/home/pshmarev/111/The_Well_of_the_Worlds.zip"));
        zip.setLevel(Deflater.BEST_COMPRESSION);
        zip.putNextEntry(new ZipEntry("The_Well_of_the_Worlds.txt"));

        BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("/home/pshmarev/111/The_Well_of_the_Worlds.origin.txt"), "utf-8"));
        Charset charset = Charset.forName("Windows-1251");
//        Charset charset = Charset.forName("utf-8");
        StringBuilder buf = new StringBuilder(0x10000);

        for (String str = reader.readLine(); str != null; str = reader.readLine()) {
            if (str.length() == 0 || str.charAt(0) == ' ') {
                zip.write('\n');
                ByteBuffer byteBuffer = charset.encode(deSpace(buf));
                zip.write(byteBuffer.array(), 0, byteBuffer.limit());
                buf.setLength(0);
                buf.append(str);
            } else {
                buf.append(' ').append(str);
            }
        }
        if (buf.length() > 0) {
            zip.write('\n');
            zip.write(charset.encode(deSpace(buf)).array());
        }
        zip.write('\n');
        zip.write('\n');
        zip.flush();
        zip.closeEntry();
        zip.close();
        reader.close();
    }

    private static String deSpace(CharSequence seq) {
        int n = 0;
        char[] bb = new char[seq.length()];
        for (int i = 0; i < seq.length(); i++) {
            char ch = seq.charAt(i);
            if (Character.isSpaceChar(ch)) {
                if (i > 0 && !Character.isSpaceChar(seq.charAt(i - 1))) {
                    bb[n++] = ch;
                }
            } else {
                bb[n++] = ch;
            }
        }
//        while (buf.length() > 0 && Character.isSpaceChar(buf.charAt(buf.length() - 1))) {
//            buf.setLength(buf.length() - 1);
//        }
        return new String(bb, 0, n);
    }
}
